package com.maxlen.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maxlen.common.utils.CopyUtils;
import com.maxlen.common.utils.PageUtils;
import com.maxlen.common.utils.Query;
import com.maxlen.goods.dao.ProductAttrValueDao;
import com.maxlen.goods.entity.ProductAttrValueEntity;
import com.maxlen.goods.entity.dto.ProductAttrValueDTO;
import com.maxlen.goods.entity.vo.ProductAttrValueVO;
import com.maxlen.goods.service.ProductAttrValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDetailList(List<ProductAttrValueEntity> productAttrValueEntities) {
        this.saveBatch(productAttrValueEntities);
    }

    @Override
    public List<ProductAttrValueEntity> baseAttrListForSpu(Long spuId) {
        List<ProductAttrValueEntity> productAttrValueEntityList = baseMapper.selectList(
                new LambdaQueryWrapper<ProductAttrValueEntity>()
                        .eq(ProductAttrValueEntity::getSpuId, spuId));
        return productAttrValueEntityList;
    }


    @Override
    @Transactional
    public void updateSpuAttr(Long spuId, List<ProductAttrValueVO> productAttrValueVO) {
        baseMapper.delete(new LambdaQueryWrapper<ProductAttrValueEntity>().eq(ProductAttrValueEntity::getSpuId, spuId));

        List<ProductAttrValueEntity> productAttrValueEntityList = CopyUtils.copyList(productAttrValueVO, ProductAttrValueEntity.class);
        List<ProductAttrValueEntity> collect = productAttrValueEntityList.stream().map(productAttrValueEntity -> {
            productAttrValueEntity.setSpuId(spuId);
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

}
